package com.glsc.ngateway.platform.service;

import com.glsc.ngateway.common.base.domain.mysql.gateway.other.EmailClient;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.EmailClientLog;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.EmailClientLogRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.EmailClientRepository;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import com.glsc.ngateway.platform.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

/**
 * @Author: zhaoxc
 * @Date: 2020/7/20 14:17
 * @Desc:
 */
@Service
public class EmailClientService {

    @Autowired
    private EmailClientRepository emailRepo;

    @Autowired
    private EmailClientLogRepository emailLogRepo;

    /**
     * 分页条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<EmailClient> findPage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "mailId";

        pageNo= PageUtil.initPageNo(pageNo);
        pageSize=PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        return emailRepo.findAll(SpecificationUtil.buildSpecification(param, EmailClient.class), pageable);
    }

    /**
     * 查找实体
     * @param id
     * @return EmailClient
     */
    public EmailClient findById(Integer id) {
        Optional<EmailClient> optional = emailRepo.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    public EmailClient saveOrUpdate(EmailClient emailClient){
        EmailClientLog log = new EmailClientLog();
        SpringUtil.copyPropertiesIgnoreNull(emailClient, log);
        log.setCreateAccount(emailClient.getOpOperator());
        log.setUpdateAccount(emailClient.getOpOperator());
        emailLogRepo.save(log);
        return emailRepo.save(emailClient);
    }


}
